<!--
 * @Author: 陈伟 291456440@qq.com
 * @Date: 2022-10-31 09:31:32
 * @LastEditors: 陈伟 chenwei@duoliheng.com
 * @LastEditTime: 2023-01-09 18:06:41
 * @FilePath: \cool.front\src\views\distributionManage\electronic\components\table2.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="table2">
    <div class="search">
      <el-row :gutter="10">
        <el-col :span="18">
          <!-- <el-tree-select
            v-model="currentOrg"
            clearable
            class="tree-select"
            :popover-width="360"
            :select-params="{
              clearable: true,
              placeholder: '请选择',
              loading: $loadingPlugin.getTreeData,
            }"
            :tree-params="{
              'expand-on-click-node': false,
              'highlight-current': true,
              'filterable': true,
              props: {
                value: 'orgSNNo',
                label: 'orgName',
                disabled: 'disabled',
              },
              data: treeData,
            }"
            @node-click="selectTreeChange"
          /> -->
          <el-select v-model="chooseOrgId" placeholder="请选择" @change="chooseOrg">
            <el-option
              v-for="(item,index) in treeData"
              :key="index"
              :label="item.orgName"
              :value="item.orgId"
            />
          </el-select>
        </el-col>
        <el-col :span="4">
          <el-button v-permission="1" @click="add">新增</el-button>
        </el-col>
      </el-row>
    </div>
    <el-table :data="tableData" border highlight-current-row @current-change.stop="currentRow">
      <el-table-column type="index" label="序号" width="50" align="center" />
      <el-table-column prop="fenceName" label="围栏名称" align="center" />
      <el-table-column prop="" label="围栏" width="60" align="center">
        <template slot-scope="scoped">
          <div class="img-container" @click="edit(scoped.row)">
            <img v-show="!scoped.row.isFence" src="@/assets/images/add.svg" alt="">
            <img v-show="scoped.row.isFence" src="@/assets/images/have.svg" alt="">
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="" label="颜色" width="40" align="center">
        <template slot-scope="scoped">
          <colorPicker v-if="scoped.row.fillColor" v-model="scoped.row.fillColor" disabled />
        </template>
      </el-table-column>
      <el-table-column prop="userNames" label="派送配送员" align="center" />
      <el-table-column prop="" label="自动派单是否开启" align="center">
        <template slot-scope="scoped">
          <el-switch
            v-model="scoped.row.isOpen"
            active-color="#13ce66"
            inactive-color="#ff4949"
            @change="active(scoped.row)"
          />
        </template>
      </el-table-column>
      <el-table-column prop="" label="操作" align="center" width="50">
        <template slot-scope="scoped">
          <!-- <el-button type="text" @click="scheduling(scoped.row)">排班</el-button> -->
          <el-button v-permission="2" type="text" @click="remove(scoped.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog
      v-el-drag-dialog
      title="排班"
      :visible.sync="visible"
      width="420px"
      append-to-body
      destroy-on-close
      @closed="visible = false"
    >
      <el-form ref="dataForm" class="form" :inline="true" :model="query" label-position="right" label-width="120px">
        <el-form-item label="当前站点：" prop="orgName">
          <el-input v-model="query.orgName" readonly />
        </el-form-item>
        <el-form-item label="待排班子围栏：" prop="fenceName">
          <el-input v-model="query.fenceName" readonly />
        </el-form-item>
        <el-form-item label="派送配送员：" prop="userIds">
          <el-select v-model="query.userIds" multiple :multiple-limit="1" placeholder="请选择" @change="chooseUserNames">
            <el-option
              v-for="(item,index) in userList"
              :key="index"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="visible = false">
          关闭
        </el-button>
        <el-button type="primary" @click="saveScheduling">
          保存
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  // import getTreeData from '@/utils/jsonTree'
  import { saveOrgFence, deleteOrgFence, queryOwnersList } from '@/api'
  import { mapGetters } from 'vuex'
  export default {
    name: 'table2',
    props: {
      tableData: {
        type: Array,
        default: []
      },
      resetNum: {
        type: Number,
        default: 0
      },
      chooseId: {
        type: Number,
        default: 0
      }
    },
    data() {
      return {
        treeData: [],
        chooseOrgId: null,
        currentItem: null,
        currentOrgItem: null,
        visible: false,
        userList: [], // 配送人
        userNames: [],
        userIds: [],
        query: {
          orgName: '',
          fenceName: '',
          userNames: [],
          userIds: []
        }
      }
    },
    computed: {
      ...mapGetters(['orgList'])
    },
    watch: {
      chooseId: {
        handler(val) {
          this.chooseOrgId = val
          this.currentOrgItem = this.treeData.filter(item => item.orgId === this.chooseOrgId)[0]
        },
        immediate: true
      }
    },
    created() {
      this.getTreeData()
    },
    methods: {
      // 获取所属机构数据
      async getTreeData() {
        const data = this.orgList.filter((item) => {
          if (item.orgType === 7) {
            return {
              label: item.orgName,
              ...item
            }
          }
        })
        // console.log(data)
        this.treeData = data
        // this.treeData = getTreeData(data)
        this.currentOrgItem = this.treeData.filter(item => item.orgId === this.chooseId)[0]
      },
      // 选择站点
      chooseOrg(value) {
        // this.currentOrgItem = value
        // console.log(value, this.currentOrg)
        this.currentOrgItem = this.treeData.filter(item => item.orgId === value)[0]
        this.$emit('chooseOrg', value)
      },
      // 选中行
      currentRow(row) {
        this.$emit('currentRow', row)
      },
      // 新增
      add() {
        if (!this.chooseOrgId) return
        this.$emit('add', this.currentOrgItem)
      },
      // 是否自动派单
      active(row) {
        this.$confirm(`是否${!row.isOpen ? '关闭' : '启用'}自动派单？`, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          // await frenceDelete({ id: row.id })
          row.isOpen = row.isOpen ? 1 : 0
          const form = {
            id: row.id,
            orgId: row.orgId,
            orgName: row.orgName,
            orgSNNo: row.orgSNNo,
            fenceName: row.fenceName, // 围栏名称
            fenceType: row.fenceType, // 围栏类型1：站点，2：配送员
            borderColor: row.borderColor, // 边界颜色
            fillColor: row.fillColor, // 填充颜色
            coordinates: row.coordinates, // 围栏范围
            fenceArea: row.fenceArea, // 围栏面积
            isOpen: row.isOpen
          }
          saveOrgFence(form).then(() => {
            this.$notify({
              title: '提示',
              message: `${!row.isOpen ? '关闭' : '启用'}成功！`,
              type: 'success',
              duration: 2000
            })
            this.$emit('chooseOrg', this.currentOrgItem.orgId)
          }).catch(err => {
            console.log(err)
            // this.$message.error(err.message)
          })
        }).catch(() => {
          row.isOpen = !row.isOpen
          this.$message.info('已取消')
        })
      },
      // 编辑
      edit(row) {
        this.$emit('currentRow', row)
      },
      // 删除
      remove(row) {
        if (row.isOpen) {
          this.$message.warning('该子围栏已开启自动派单功能，不能删除')
          return
        }
        this.$confirm('确定删除此围栏吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          await deleteOrgFence({ id: row.id }).then(() => {
            this.$notify({
              title: '提示',
              message: '删除成功',
              type: 'success',
              duration: 2000
            })
            this.$emit('chooseOrg', this.currentOrgItem.orgId)
          }).catch(err => {
            console.log(err)
            // this.$message.error(err.message)
          })
        }).catch(() => {
          this.$message.info('已取消删除')
        })
      },
      // 排班
      async scheduling(row) {
        const res = await queryOwnersList({ orgId: row.orgId, utype: 32 })
        console.log(res)
        this.userList = res.data
        console.log(row)
        this.currentItem = row
        this.query.orgName = row.orgName
        this.query.fenceName = row.fenceName
        const userIds = row.userIds ? row.userIds.split(',') : []
        this.query.userIds = userIds.map(item => {
          return Number(item)
        })
        // this.query.userIds = userIds
        console.log(this.query.userIds)
        this.visible = true
      },
      // 选择配送人
      chooseUserNames(value) {
        this.userNames = []
        this.userIds = []
        const list = this.userList.filter(items => {
          // 循环拿到新数组的值 使用includes函数去原数组中查找
          if (value.includes(items.userId)) {
            // 判断结构为true进入判断 并把内容返回给新数组
            return items.userName
          }
        })
        console.log(list)
        list.forEach(item => {
          this.userNames.push(item.userName)
          this.userIds.push(item.userId)
        })
        console.log(this.userNames)
        console.log(this.userIds)
      },
      // 保存
      async saveScheduling() {
        if (!this.userNames.length || !this.userNames.length) {
          this.$message.error('派送配送员不能为空')
          return
        }
        this.currentItem.isOpen = this.currentItem.isOpen ? 1 : 0
        const form = {
          id: this.currentItem.id,
          orgId: this.currentItem.orgId,
          orgName: this.currentItem.orgName,
          orgSNNo: this.currentItem.orgSNNo,
          fenceName: this.currentItem.fenceName, // 围栏名称
          fenceType: this.currentItem.fenceType, // 围栏类型1：站点，2：配送员
          borderColor: this.currentItem.borderColor, // 边界颜色
          fillColor: this.currentItem.fillColor, // 填充颜色
          coordinates: this.currentItem.coordinates, // 围栏范围
          fenceArea: this.currentItem.fenceArea, // 围栏面积
          isOpen: this.currentItem.isOpen,
          userNames: this.userNames.join(','),
          userIds: this.userIds.join(',')
        }
        await saveOrgFence(form).then(() => {
          this.$notify({
            title: '提示',
            message: '保存成功',
            type: 'success',
            duration: 2000
          })
          this.visible = false
          this.$emit('chooseOrg', this.currentOrgItem.orgId)
        }).catch(err => {
          console.log(err)
          // this.$message.error(err.message)
        })
      }
    }
  }
</script>

<style lang="scss" scoped>
.img-container {
  display: flex;
  align-items: center;
  justify-content: center;
  img {
    cursor: pointer;
  }
}
.table2 {
  height: 100%;
  padding-left: 10px;
}
.search {
  margin-bottom: 10px;
  .el-select {
    width: 100%;
  }
}
/deep/ .el-table {
  height: calc(100% - 40px);
}
/deep/ .el-table__body-wrapper {
  height: calc(100% - 40px);
  overflow: hidden;
  &:hover {
    overflow: auto;
  }
}
/deep/ .cell {
  overflow: hidden;
  font-weight: normal;
  text-overflow: ellipsis;
  white-space: nowrap;/* 强制在同一行内显示所有文本，直到文本结束或者遭遇br标签对象才换行。 */

  /* 超出部分隐藏 */

  /* 隐藏部分以省略号代替 */
}
</style>
